# coding:utf-8
# 账号管理器
# 不做内存缓存, 直接读写数据库

import traceback, datetime
import glog, gdb
from db_tables import *
from sqlalchemy import and_, or_

# 一个账号下最多的角色数量
# 数据库最多是3个, 如果要增加, 需要同时修改数据库
MAX_ACCOUNT_ROLES = 3

# 账号状态
ACCST_NORMAL = 0		# 正常
ACCST_FREEZE = 1		# 冻结
ACCST_BAN = 2		# 禁止


def init ():
	pass


# 创建账号
def create_account (account, password):
	res = db_create_account(account, password)
	if res:	glog.log("account_mgr>create_account %s" % account)
	else:	glog.log("account_mgr>create_account %s FEILED" % account)
	return res


# 冻结账号
def freeze_account (account):
	res = db_set_state(account, ACCST_FREEZE)
	if res:	glog.log("account_mgr>freeze_account %s" % account)
	else:	glog.log("account_mgr>freeze_account %s FEILED" % account)
	return res


# 解冻账号
def unfreeze_account (account):
	if is_ban():
		glog.log("account_mgr>unfreeze_account %s FEILED (in status BAN)" % account)
		return False

	res = db_set_state(account, ACCST_NORMAL)
	if res:	glog.log("account_mgr>unfreeze_account %s" % account)
	else:	glog.log("account_mgr>unfreeze_account %s FEILED" % account)
	return res


# 禁止账号
def ban_account (account):
	res = db_set_state(account, ACCST_BAN)
	if res:	glog.log("account_mgr>ban_account %s" % account)
	else:	glog.log("account_mgr>ban_account %s FEILED" % account)
	return res


# 账号是否正常状态
def is_normal (account):
	return db_get_state(account) == ACCST_NORMAL

# 账号是否被Ban
def is_ban (account):
	return db_get_state(account) == ACCST_BAN


# 检测密码
def check_password (account, password):
	pwd = db_get_password(account)

	# 没有账号的情况
	if not pwd:
		glog.log("account_mgr>no this account: %s" % account) 
		return False
	
	return (pwd == password)


# ------------------------------------------------------
def db_create_account (account, password):
	create_time = datetime.datetime.now()
	last_login_time = -1
	state = ACCST_NORMAL
	
	ses = gdb.get_session()
	try:
		ses.add(DBAccount(account, password, create_time, last_login_time, state))
		ses.commit()
		return True
	except Exception, e:
		print traceback.format_exc()
		ses.rollback()
		return False


def db_get_password (account):
	ses = gdb.get_session()
	acc = ses.query(DBAccount).filter_by(account=account).first()
	if acc:
		return acc.password


def db_get_state (account):
	ses = gdb.get_session()
	acc = ses.query(DBAccount).filter_by(account=account).first()
	if acc:
		return acc.state


def db_set_state (account, state):
	ses = gdb.get_session()
	acc = ses.query(DBAccount).filter_by(account=account).first()
	if acc:
		acc.state = state
		ses.commit()
		return True
	return False
	